﻿#region Header

// Written by Tobias Lekman, 2008. For more information and contact details, see http://www.lekman.com.
// 
// File released under Microsoft Public License (Ms-PL). For full details see http://www.microsoft.com/opensource/licenses.mspx
// 
// Conditions and Limitations
// 
// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
// 
// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
// 
// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
// 
// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
// 
// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 

#endregion

#region Using Statements

using System;
using System.Timers;
using System.Web.Caching;
using Microsoft.SharePoint;

#endregion

namespace CodePlex.Lekman.SharePoint.CacheDependencies
{
    /// <summary>
    /// Base class for making cache dependencies 
    /// </summary>
    /// <remarks>
    /// Based on an idea from "The Kid" at http://blog.thekid.me.uk/archive/2008/09/23/sharepoint-caching-and-cachedependency.aspx.
    /// </remarks>
    public abstract class SPObjectCacheDependency : CacheDependency
    {
        #region Fields

        private readonly Timer timer;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the SPObjectCacheDependency class.
        /// </summary>
        /// <param name="interval">The interval in milliseconds to check the underlying object for changes.</param>
        protected SPObjectCacheDependency(double interval)
        {
            //Start check timer
            timer = new Timer(interval)
                        {
                            AutoReset = true
                        };
            timer.Elapsed += OnTimerElapsed;
            timer.Start();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the <see cref="SPObjectCacheDependencyEventArgs"/> containing the information about the current SharePoint object.
        /// </summary>
        protected abstract SPObjectCacheDependencyEventArgs EventArgs{get;}

        #endregion

        #region Methods

        /// <summary>
        /// Retrieves a unique identifier for a <see cref="System.Web.Caching.CacheDependency" /> object formed of the ID of the list, its parent <see cref="SPWeb"/> and <see cref="SPSite"/>.
        /// </summary>
        /// <returns>
        /// The unique identifier for the <see cref="System.Web.Caching.CacheDependency" /> object.
        /// </returns>
        public abstract override string GetUniqueID();

        /// <summary>
        /// Determines if a specific list is different in version than the contained object.
        /// </summary>
        /// <param name="source">The object instance to check for changes.</param>
        /// <returns>true if the object has changed.</returns>
        protected abstract bool HasObjectChanged(object source);

        /// <summary>
        /// Checks periodically if the list has changed.
        /// </summary>
        /// <param name="sender">The timer object.</param>
        /// <param name="e">An <see cref="ElapsedEventArgs"/> object containing the event data.</param>
        private void OnTimerElapsed(object sender,
                                    ElapsedEventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(EventArgs.SiteId))
                {
                    using (SPWeb web = site.OpenWeb(EventArgs.WebId))
                    {
                        SPList list = web.Lists[EventArgs.ListId];
                        if (EventArgs.ItemId < 1)
                        {
                            ObjectChanged(list);
                            return;
                        }
                        ObjectChanged(list.GetItemById(EventArgs.ItemId));
                    }
                }
            }
            catch (ArgumentException)
            {
                //Object deleted.
                ObjectChanged(null);
            }
        }

        /// <summary>
        /// Checks if an object has changed and notifies the base cache dependency object of the change.
        /// </summary>
        /// <param name="source">The object which might have changed.</param>
        private void ObjectChanged(object source)
        {
            if (HasObjectChanged(source) ||
                source == null)
            {
                timer.Stop();
                NotifyDependencyChanged(this,
                                        EventArgs);
            }
        }

        #endregion
    }
}